/*
 * Copyright 2011 Sina.
 *
 * Licensed under the Apache License and Weibo License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.open.weibo.com
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.appointmentregister.sina;

import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.appointmentregister.sina.AsyncWeiboRunner.RequestListener;
import com.cmcc.aregister.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.Toast;


/**
 * A dialog activity for sharing any text or image message to weibo. Three
 * parameters , accessToken, tokenSecret, consumer_key, are needed, otherwise a
 * WeiboException will be throwed.
 * 
 * ShareActivity should implement an interface, RequestListener which will
 * return the request result.
 * 
 * @author ZhangJie (zhangjie2@staff.sina.com.cn)
 */

public class ShareActivity extends Activity implements OnClickListener, RequestListener {
//	private static final String TAG = "ShareActivity";
	private Button mSend, close;

    private String mContent = "";
    private String mAccessToken = "";
    private String mTokenSecret = "";

    public static final String EXTRA_WEIBO_CONTENT = "com.weibo.android.content";
    public static final String EXTRA_PIC_URI = "com.weibo.android.pic.uri";
    public static final String EXTRA_ACCESS_TOKEN = "com.weibo.android.accesstoken";
    public static final String EXTRA_TOKEN_SECRET = "com.weibo.android.token.secret";

    public static final int WEIBO_MAX_LENGTH = 140;
    
    private boolean canSend = true;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        closeSoftKeys();
        this.setContentView(R.layout.share_mblog_view);

        Intent in = this.getIntent();
//        mPicPath = in.getStringExtra(EXTRA_PIC_URI);
        mContent = in.getStringExtra(EXTRA_WEIBO_CONTENT);
        mAccessToken = in.getStringExtra(EXTRA_ACCESS_TOKEN);
        mTokenSecret = in.getStringExtra(EXTRA_TOKEN_SECRET);

        AccessToken accessToken = new AccessToken(mAccessToken, mTokenSecret);
        Weibo weibo = Weibo.getInstance();
        weibo.setAccessToken(accessToken);
		close = (Button) this.findViewById(R.id.btnClose);
		close.setOnClickListener(this);
		mSend = (Button) this.findViewById(R.id.btnSend);
		mSend.setOnClickListener(this);
    }
    
    private String getPhotoFileName() {   
    	Date date = new Date(System.currentTimeMillis());   
    	SimpleDateFormat dateFormat = new SimpleDateFormat(   
    			"HH:mm:ss"); 
    	String randomTime = dateFormat.format(date);
    	return " " + randomTime;  
    } 
    
    private void sending(){
		showProgressDlg2(getString(R.string.dialog_sending));
	}
	public void progressRun2(){
		Weibo weibo = Weibo.getInstance();
        try {
            if (!TextUtils.isEmpty((String) (weibo.getAccessToken().getToken()))) {
            	mContent = getString(R.string.weibo_default_words) + getPhotoFileName();
//            	Log.i(TAG,"mContent:" + mContent);
                if(mContent.equals("")){
        			mContent = getString(R.string.weibo_default_words) + getPhotoFileName();
        		}
                update(weibo, Weibo.getAppKey(), mContent, "", "");
                /*if (!TextUtils.isEmpty(mPicPath)) {
                    upload(weibo, Weibo.getAppKey(), this.mPicPath, this.mContent, "", "");

                } else {
                    // Just update a text weibo!
                    update(weibo, Weibo.getAppKey(), mContent, "", "");
                }*/
            } else {
                Toast.makeText(this, this.getString(R.string.please_login), Toast.LENGTH_LONG);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (WeiboException e) {
            e.printStackTrace();
        }
	}
    
    @Override
    public void onClick(View v) {
        int viewId = v.getId();

        if (viewId == R.id.btnClose) {
            finish();
        } else if (viewId == R.id.btnSend) {
        	if(canSend){
				sending();
			}else{
				showSingleAlertDlg(getString(R.string.dialog_warning), getString(R.string.dialog_textnumber_too_more), getString(R.string.dialog_close));
			}
        }
    }

    private String upload(Weibo weibo, String source, String file, String status, String lon,
            String lat) throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", source);
        bundle.add("pic", file);
        bundle.add("status", status);
        if (!TextUtils.isEmpty(lon)) {
            bundle.add("lon", lon);
        }
        if (!TextUtils.isEmpty(lat)) {
            bundle.add("lat", lat);
        }
        String rlt = "";
        String url = Weibo.SERVER + "statuses/upload.json";
        AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);
        weiboRunner.request(this, url, bundle, Utility.HTTPMETHOD_POST, this);

        return rlt;
    }

    private String update(Weibo weibo, String source, String status, String lon, String lat)
            throws MalformedURLException, IOException, WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", source);
        bundle.add("status", status);
        if (!TextUtils.isEmpty(lon)) {
            bundle.add("lon", lon);
        }
        if (!TextUtils.isEmpty(lat)) {
            bundle.add("lat", lat);
        }
        String rlt = "";
        String url = Weibo.SERVER + "statuses/update.json";
        AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);
        weiboRunner.request(this, url, bundle, Utility.HTTPMETHOD_POST, this);
        return rlt;
    }

    @Override
    public void onComplete(String response) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(ShareActivity.this, R.string.send_sucess, Toast.LENGTH_LONG).show();
            }
        });

        this.finish();
    }

    @Override
    public void onIOException(IOException e) {
        // TODO Auto-generated method stub
    	Toast.makeText(
                ShareActivity.this,
                String.format(ShareActivity.this.getString(R.string.send_failed) + ":%s",
                        e.getMessage()), Toast.LENGTH_LONG).show();
//    	Log.i(TAG,"onIOException:" + e.getMessage());
    }

    @Override
    public void onError(final WeiboException e) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(
                        ShareActivity.this,
                        String.format(ShareActivity.this.getString(R.string.send_failed) + ":%s",
                                e.getMessage()), Toast.LENGTH_LONG).show();
//                Log.i(TAG,"onError:" + e.getMessage());
            }
        });

    }
    
    public void showSingleAlertDlg(String title,String msg,String posTitle){
		new AlertDialog.Builder(this)
		.setTitle(title)
		.setMessage(msg)
		.setIcon(android.R.drawable.ic_dialog_info)
		.setCancelable(false)
		.setPositiveButton(posTitle, new DialogInterface.OnClickListener() {	
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
//				singleBtnWork();
			}
		})
		.create()
		.show();
	}
    
    public void showProgressDlg2(String msg){
    	final ProgressDialog loadingDlg = new ProgressDialog(this);
		loadingDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		loadingDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
		loadingDlg.setMessage(msg);
		loadingDlg.setCancelable(true);
		loadingDlg.show();
		new Thread(){
			public void run(){
				try {
					progressRun2();
				} catch (Exception e) {
					loadingDlg.dismiss();
				}
				loadingDlg.dismiss();
			}
		}.start(); 
		loadingDlg.setOnDismissListener(new DialogInterface.OnDismissListener(){

			@Override
			public void onDismiss(DialogInterface dialog) {
				// TODO Auto-generated method stub
//				doWork2();
			} 
			
		});
	}
    
    /**
	 * 隐藏软件盘
	 * @param a
	 */
	private void closeSoftKeys(){
		((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
		.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}
}
